# -*- coding: utf-8 -*-
import bs4, requests, re, json, lxml
from requests.cookies import RequestsCookieJar
from WorkflowScript.bug_branch_task_comparison import get_jira_summary

# 控制台输出移除SSL认证警告
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

git_url = 'https://git.mingyuanyun.com/users/sign_in'

headers = {
    'Host': 'git.mingyuanyun.com',
    'Connection': 'keep-alive',
    'Accept': '*/*',
    'X-Requested-With': 'XMLHttpRequest',
    'X-PJAX': 'true',
    'X-AUSERNAME': 'wup06',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9',
}

LoginHeaders = {
    'Host': 'git.mingyuanyun.com',
    'Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Sec-Fetch-Site': 'none',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-Dest': 'document',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9'
}
# 设置代理，用户fiddler抓取
proxies = {
    "http": "127.0.0.1:8888"
}
def tags_val(tag, key='', index=0):
    '''
    return html tag list attribute @key @index
    if @key is empty, return tag content
    '''
    if len(tag) == 0 or len(tag) <= index:
        return ''
    elif key:
        txt = tag[index].get(key)
        return txt.strip(' \t\r\n') if txt else ''
    else:
        txt = tag[index].text
        return txt.strip(' \t\r\n') if txt else ''


def tag_val(tag, key=''):
    '''
    return html tag attribute @key
    if @key is empty, return tag content
    '''
    if tag is None:
        return ''
    elif key:
        txt = tag.get(key)
        return txt.strip(' \t\r\n') if txt else ''
    else:
        txt = tag.text
        return txt.strip(' \t\r\n') if txt else ''

# 初始化session，后续请求就能自动带上cookies
sess = requests.session()

def get_token():
    resp = sess.get(
        url=git_url,
        headers=LoginHeaders, proxies=proxies, verify=False)
    # print resp.status_code

    #通过bs4解析html
    soup = bs4.BeautifulSoup(resp.text, 'lxml')
    tags = soup.select('[name="csrf-token"]')
    if resp.status_code == 200:
        token = tags_val(tags, "content", 0)
        return token
    else:
        print ('token获取失败')


# 登录
def login():
    token = get_token()
    header = {
        'Host': 'git.mingyuanyun.com',
        'Connection': 'keep-alive',
        'Content-Length': '170',
        'Cache-Control': 'max-age=0',
        'Upgrade-Insecure-Requests': '1',
        'Origin': 'https://git.mingyuanyun.com',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'Sec-Fetch-Site': 'same-origin',
        'Sec-Fetch-Mode': 'navigate',
        'Sec-Fetch-User': '?1',
        'Sec-Fetch-Dest': 'document',
        'Referer': 'https://git.mingyuanyun.com/users/sign_in',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
    }
    data = {
        'utf8': '✓',
        'authenticity_token': token,
        'username': 'wup06',
        'password': 'xxxxxx',
    }
    cookie_jar = RequestsCookieJar()
    # print(sess.cookies(['_gitlab_session']))
    # 将cookiejar转换为字典形式的数据:{'_gitlab_session': '4774884897f7ea1ab2a48ed2caab4fa6'}
    get_cookies_dict = requests.utils.dict_from_cookiejar(sess.cookies)
    cookie_jar.set("sidebar_collapsed", "false")
    # for k,v in get_cookies_dict.items():
    #     cookie_jar.set(k, v)
    cookies = cookie_jar

    resp = sess.post(
        url="https://git.mingyuanyun.com/users/auth/ldapmain/callback",
        headers=header, data=data, cookies = cookies, proxies=proxies, verify=False)
    # print resp.status_code
    if resp.status_code == 200:
        pass
    else:
        print ('登录失败')

def get_content(batch,datatime):
    url = "https://git.mingyuanyun.com/platform/gzl/gzlERP/commits/"+batch
    # url = "https://git.mingyuanyun.com/platform/gzl/gzlERP/commits/hotfix/2.0.27.15_%E7%A8%B3%E5%AE%9A%E7%89%88%E4%BF%AE%E5%A4%8D%E5%88%86%E6%94%AF20201111"
    # "2.0.27.15_稳定版修复分支20201111"
    resp = sess.get(url)
    # 通过bs4解析html
    soup = bs4.BeautifulSoup(resp.text, 'lxml')
    tags = soup.select('[class="commit-content qa-commit-content"]')
    # tags = soup.select('[class="commit-content qa-commit-content"]')
    if resp.status_code == 200:
        result = []
        for a in tags:
            # 得到class="commit-content qa-commit-content"的父元素列表
            for parent in a.parents:
                # 获取父元素中data-day的属性值
                data = parent.get('data-day')
                # data-day值不为None且大于指定日期
                if data is not None and data > datatime:
                    # 获取a标签的元素，以便得到a标签的text
                    tags_a = a.select('a')
                    summary = []
                    for tag_a in tags_a:
                        author = tag_a.get("class")
                        more = tag_a.parent.pre

                        if author is not None and "commit-author-link" in author:
                            summary.append(" --"+tag_a.text)
                        else:
                            if more is not None:
                                summary.append(more.text)
                            summary.append(tag_a.text)
                        # print(x.text)
                    # print("".join(summary))
                    result.append("".join(summary))
        # 返回已提交bug的列表
        return result
    else:
        print ('获取失败')
        return None

def git_action(batch, datatime):
    login()
    # # 分支名称
    # batch = "2.0.27.15_稳定版修复分支20201111"
    # # 上次发包日期，从RDC发包可以获取
    # datatime = "2020-11-09"
    return get_content(batch, datatime)

# 执行git和jira内容对比
def main(batch,datatime,sprint_name,version):
    # git中已提交的jira，返回列表["GZL-19882 ERPFD-26407【11sp1】【2.0.27.15】【产品优化】流程被打回后，重新发起报错 --肖成毅",....]
    git_content = git_action(batch, datatime)
    # 指定sprint和指定关键字的jira内容，返回字典{"GZL-19882":"ERPFD-26407【11sp1】【2.0.27.15】【产品优化】流程被打回后，重新发起报错 --肖成毅",...}
    jira_content = get_jira_summary.jira_action(sprint_name, version)
    git_exist = []
    git_no_exist = []
    for k, v in jira_content.items():
        # v.split("】")[-1].split(" --")[0]，通过“ERPFD-26407【11sp1】【2.0.27.15】【产品优化】流程被打回后，重新发起报错 --肖成毅”切分后得到“流程被打回后，重新发起报错”后与git列表内容对比
        split_title = v.split("】")[-1].split(" --")[0]
        # 如果jira编号在git的提交列表里面，则打印，如果编号或者内容都能匹配到git列表里面，则打印出来
        if True in map(lambda x: k in x, git_content) or True in map(lambda x: split_title in x, git_content):
            git_exist.append(k + v)
        else:
            git_no_exist.append(k + v)

    print(u"\ngit现有问题-------------------------------------")
    for summary in git_content:
        print(summary.replace(u'\xa0', u' '))
        pass

    print(u"\n已提交jira-------------------------------------")
    for exist in git_exist:
        print(exist)

    print(u"\n未提交jira-------------------------------------")
    for no_exist in git_no_exist:
        print(no_exist)

# if __name__ == '__main__':
#     # 分支名称
#     batch = "2.0.27.15_稳定版修复分支20201111"
#     # 上次发包日期，从RDC发包可以获取
#     datatime = "2020-11-09"
#     git_action(batch,datatime)